package com.monolithiot.sso.common.util;

import com.monolithiot.sso.common.context.Constants;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 2018/12/12 Create by 郭文梁
 * CookieUtil
 * Cookie工具类
 *
 * @author 郭文梁
 * @date 2018/12/12
 */
public class CookieUtil {
    /**
     * 获取免登录Cookie
     *
     * @param liveTime 免登录时长 (秒)
     */
    public static Cookie obtainRememberCookie(int liveTime, String accessToken) {
        Cookie cookie = new Cookie(Constants.Key.REMEMBER_COOKIE_NAME, accessToken);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(liveTime);
        return cookie;
    }

    /**
     * 从Request中获取RememberCookie
     *
     * @param request Http请求对象
     * @return Cookie
     */
    public static Cookie rememberCookirFromRequest(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        List<Cookie> rememberCookies = Arrays.stream(cookies)
                .filter(Objects::nonNull)
                .filter(ck -> Constants.Key.REMEMBER_COOKIE_NAME.equalsIgnoreCase(ck.getName()))
                .collect(Collectors.toList());
        return rememberCookies.size() >= 1 ? rememberCookies.get(0) : null;
    }
}
